package com.atguigu.gmall.common.fastdfs;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 操作fastdsf的工具类
 * @author 搭忆长安
 * @version 1.0
 * @date 2021年06月28日 19:37
 * @ClassName:FastDfsClient
 * @Description: TODO
 */
@Component
public class FastDfsClient {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String upload(MultipartFile file)throws Exception{
        /**
         * 附加参数
         *file.getInputStream()://文件数据流
         *   file.getSize()://文件大小
         *   StringUtils.getFilenameExtension(file.getOriginalFilename())://文件拓展名
         *
         */
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
                StringUtils.getFilenameExtension(file.getOriginalFilename()), null);
         //返回全量路径
        return storePath.getFullPath();
    }
    /**
     * 文件下载
     * @return
     */
    public byte[] download(String groupName,String path)throws Exception{
        //下载文件
        InputStream inputStream=fastFileStorageClient.downloadFile(groupName, path, new DownloadCallback<InputStream>() {

            @Override
            public InputStream recv(InputStream ins) throws IOException {
                return ins;
            }
        });
        //声明输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //声明缓冲区
        byte[] buffer = new byte[1024];
        //定义每次读取的数据长度
        int length = 0;
        //输出流转输出流
        while((length=inputStream.read(buffer))!=-1){
            //输出流写入
            byteArrayOutputStream.write(buffer,0,length);
        }
        //返回字节码
        return byteArrayOutputStream.toByteArray();
    }
    public void delete(String groupName,String path){
        fastFileStorageClient.deleteFile(groupName,path);
    }
}
